// https://thebookofshaders.com/06/?lan=ch
import { 
  Camera,  
  Color,  
  Mesh, 
  PlaneBufferGeometry, 
  Scene, 
  ShaderMaterial, 
  Vector3, 
  WebGLRenderer 
} from "three"

const canvas = document.createElement('canvas')
document.body.appendChild(canvas)
canvas.style.width = '100vw'
canvas.style.height = '100vh'

const scene = new Scene()
const renderer = new WebGLRenderer({
  antialias: true,
  canvas
})
renderer.autoClearColor = false

const camera = new Camera()
camera.position.z = 1
const plane = new PlaneBufferGeometry(2, 3)

// 片段着色器
const fragmentShader = `
#include <common>

uniform vec2 u_resolution;
uniform float u_time;

void main() {
  vec2 st = gl_FragCoord.xy / u_resolution.xy;
  vec3 color = vec3(0.0);

  
  // // 过滤x轴  x > 0.1 ? 0 : 1 
  // float left = step(0.1, st.x);
  // // 过滤y轴 y > 0.1 ? 0 : 1
  // float bottom = step(0.1, st.y);
  // left * bottom 效果相当于逻辑 AND
  // 当 x,y 都为 1.0 时乘积才能是 1.0
  // color = vec3(left * bottom);
  
  // 简写效果 
  vec2 borders = step(vec2(0.1), st);
  float pct = borders.x * borders.y;

  // 注意是取 0.9 - 1.0 之间的值
  vec2 topRight = step(vec2(0.1), 1.0 - st);
  // 注意是自乘
  pct *= topRight.x * topRight.y;

  color = vec3(pct);

  gl_FragColor = vec4(color, 1.0);
}
`

// const material = new MeshBasicMaterial({ color: 'red' })
const uniforms = {
  u_time: { value: 0 },
  u_resolution: { value: new Vector3() },
}
const material = new ShaderMaterial({
  fragmentShader,
  uniforms
})
scene.add(new Mesh(plane, material))

function render(time) {
  // 转化成秒
  time *= 0.001

  uniforms.u_time.value = time
  const canvas = renderer.domElement
  uniforms.u_resolution.value.set(canvas.width, canvas.height, 1)

  renderer.render(scene, camera)

  requestAnimationFrame(render)
}

requestAnimationFrame(render)